
package cn.xnatural.app;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.LongAdder;
import java.util.function.BiConsumer;

/**
 * 统计每时间段的处理个数
 */
public class Counter {
    protected final BiConsumer<String, LongAdder> fn;
    protected final String countByPattern;
    protected volatile String time;
    protected volatile LongAdder count = new LongAdder();

    public Counter(String countByPattern, BiConsumer<String, LongAdder> fn) {
        this.countByPattern = countByPattern;
        this.fn = fn;
        this.time = new SimpleDateFormat(countByPattern).format(new Date());
    }

    public Counter() {
        this("MM-dd HH", (time, count) -> {
            LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME).info("{} handle count {}", time, count);
        });
    }


    public void increment() {
        String hStr = new SimpleDateFormat(countByPattern).format(new Date());

        if (!time.equals(hStr)) {
            String oldTime = null;
            LongAdder oldCount = null;
            synchronized (this) {
                if (!time.equals(hStr)) {
                    oldTime = time; time = hStr;
                    oldCount = count; count = new LongAdder();
                }
            }
            if (oldTime != null) {
                if (fn != null) fn.accept(oldTime, oldCount);
            }
        }
        count.increment();
    }
}
